Выполнить задачу с использованием структуры «текстовый файл» (в файле хранятся целые числа по несколько в строке). Вычислить сумму нечётных элементов — C#(Си шарп)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
  
const string TEXT = @"1 2 3 4
  
5";
  
var file = new TextFile("file.txt");
await file.Create(TEXT);
  
var sum = 0L;
await foreach (var line in file.Read())
{
    sum += line
        .Split(' ', StringSplitOptions.RemoveEmptyEntries)
        .Select(int.Parse)
        .Where(x => x % 2 == 1)
        .Sum();
}
Console.WriteLine(sum);
  
internal readonly record struct TextFile(string FilePath)
{
    public async Task Create(string text) => await File.WriteAllTextAsync(FilePath, text);
  
    public async IAsyncEnumerable<string> Read()
    {
        using var stream = new StreamReader(FilePath, new FileStreamOptions
        {
            Access = FileAccess.Read,
            Mode = FileMode.Open,
            Share = FileShare.Read,
            Options = FileOptions.Asynchronous | FileOptions.SequentialScan,
        });
  
        while (!stream.EndOfStream)
        {
            yield return await stream.ReadLineAsync();
        }
    }
}

Leave a Comment